package com.sgb.kjwl.view.ui.activity.self.driver;

import android.content.Context;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppAddProprietaryDriverActivityBinding;
import com.sgb.kjwl.model.entity.self.MotorcadeSimpleEntity;
import com.sgb.kjwl.model.entity.self.ProprietaryDriverEntity;
import com.sgb.kjwl.model.entity.self.VerifyDriverEntity;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.adapter.self.AddProDriverListAdapter;
import com.sgb.kjwl.view.widget.transport.AddDriverHelpDialog;
import com.sgb.kjwl.view.widget.transport.ChooseMotorcadeDialog;
import com.sgb.kjwl.viewmodel.self.driver.AddProDriverModel;
import com.sgb.link.router.PathDriver;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static com.sgb.link.router.PathDriver.AddProprietaryDriverActivity;

/**
 * Describe:    添加自营司机（搜索列表页）
 * Author:  yangLei
 * Date:    2021/10/12
 */
@Route(path = AddProprietaryDriverActivity)
public class AddProprietaryDriverActivity extends BaseActivity<AddProDriverModel, AppAddProprietaryDriverActivityBinding> {
    @Autowired(name = RouterKey.TYPE, desc = "类型（0企业  1团队）")
    public String type;
    private AddDriverHelpDialog helpDialog;
    private ChooseMotorcadeDialog addDialog;
    /**
     * 当前搜索的手机号
     */
    private String currPhone;
    private VerifyDriverEntity currDriver;

    private List<VerifyDriverEntity> driverEntities = new ArrayList<>();
    private AddProDriverListAdapter listAdapter;

    @Override
    protected int layoutId() {
        return R.layout.app_add_proprietary_driver_activity;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(AddProDriverModel.class);
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        initViews();
        initEvents();
    }

    private void initViews() {
        mBinding.includeTitle.titleView.setText("添加自营司机");
        mBinding.includeTitle.rightView.setText("帮助");

        listAdapter = new AddProDriverListAdapter(this, driverEntities);
        mBinding.list.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.list);
        mBinding.list.setAdapter(listAdapter);
        listAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.add_btn) {
                if (UserOperating.getInstance().isCompany()) {
                    //公司身份，先请求车队信息
                    mViewModel.requestMotorcadeList(AddProprietaryDriverActivity.this);
                } else if (UserOperating.getInstance().isTeam()) {
                    //团队身份，直接请求添加接口
                    mViewModel.newAddDriver(AddProprietaryDriverActivity.this, currDriver.getUserNo());
                }
            }
        });
    }

    private void initEvents() {
        mBinding.setOnClick(this::onClick);
        mBinding.includeTitle.ivBack.setOnClickListener(v -> finish());
        mBinding.includeTitle.rightView.setOnClickListener(this::onClick);

        mViewModel.motorcadeListLD.observe(this, list -> {
            motorcadeListRequestResult(list);
        });

        mViewModel.driverLD.observe(this, verifyDriverEntity -> handleSearchDriverResult(verifyDriverEntity));

        mViewModel.addLD.observe(this, aBoolean -> {
            successAddRefresh();
        });
    }

    /**
     * 添加成功刷新页面
     */
    private void successAddRefresh() {
        EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_REFRESH_PRO_DRIVER, null));
        if (checkInputPhoneNumber()) {
            mViewModel.searchDriverByPhone(this, currPhone);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_PRO_DRIVER) {
            if (checkInputPhoneNumber()) {
                mViewModel.searchDriverByPhone(this, currPhone);
            }
        }
    }

    /**
     * 根据搜索结果处理界面显示
     *
     * @param driverEntity
     */
    private void handleSearchDriverResult(VerifyDriverEntity driverEntity) {
        if (driverEntity != null && driverEntity.getStatus() != null) {
            driverEntity.setPhone(currPhone);
            currDriver = driverEntity;
            //1允许添加 2司机已经添加 3未认证司机 4未注册账号
            switch (driverEntity.getStatus()) {
                case 1:
                case 2:
                    showDriverInfo(driverEntity);
                    break;
                case 3:
                case 4:
                    showDriverUnregister(driverEntity);
                    break;
            }
        } else {
            currDriver = null;
        }
    }

    /**
     * 司机未注册时的显示逻辑
     *
     * @param driverEntity
     */
    private void showDriverUnregister(VerifyDriverEntity driverEntity) {
        mBinding.list.setVisibility(View.GONE);
        mBinding.unregisterLayout.setVisibility(View.VISIBLE);
        if (driverEntity.getStatus() != null) {
            if (driverEntity.getStatus() == 3) {
                mBinding.helpRegister.setVisibility(View.GONE);
                mBinding.resultTv.setText("该账号未认证司机，无法添加");
            } else if (driverEntity.getStatus() == 4) {
                mBinding.helpRegister.setVisibility(View.VISIBLE);
                mBinding.resultTv.setText("该账号未注册经营帮平台");
            }
        }
    }

    /**
     * 显示搜索出来的司机信息
     */
    private void showDriverInfo(VerifyDriverEntity driverEntity) {
        mBinding.list.setVisibility(View.VISIBLE);
        mBinding.unregisterLayout.setVisibility(View.GONE);
        driverEntities.clear();
        driverEntities.add(driverEntity);
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_view://展示帮助弹窗
                if (helpDialog == null) {
                    helpDialog = AddDriverHelpDialog.newInstance(this);
                }
                if (!helpDialog.isShowing()) {
                    helpDialog.show();
                }
                break;

            case R.id.search_btn://按手机号搜索
                if (checkInputPhoneNumber()) {
                    mViewModel.searchDriverByPhone(this, currPhone);
                }
                break;

            case R.id.help_register://未注册平台账号，帮他注册
                if (currDriver != null && !TextUtils.isEmpty(currDriver.getPhone()))
                    ARouter.getInstance().build(PathDriver.NewProprietaryDriverActivity)
                            .withString(RouterKey.STRING, currDriver.getPhone())
                            .navigation(this);

                break;
        }
    }

    /**
     * 检查输入的手机号是否为11位数字
     */
    private boolean checkInputPhoneNumber() {
        String num = mBinding.phoneNumEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(num) && num.length() == 11) {
            hideKeyboard();
            currPhone = num;
            return true;
        } else {
            MToast.showToast(getApplicationContext(), "请使用正确格式的手机号搜索");
            currPhone = "";
            return false;
        }
    }

    private void motorcadeListRequestResult(List<MotorcadeSimpleEntity> list) {
//        if (list == null || list.size() < 1) {
//            //没有车队时弹窗提示
//            new RoundDialog.Builder(this)
//                    .title("提示")
//                    .content("添加司机需要选择车队，当前无可用车队，请先至“车队管理”添加自营车队")
//                    .confirm("确定")
//                    .singleBtn(true)
//                    .cancelable(false)
//                    .show();
//        } else {
        //有车队可选
        if (list != null && list.size() > 0) {
            ChooseMotorcadeDialog.setDefaultItem(list, "");
        }
        if (addDialog == null) {
            addDialog = ChooseMotorcadeDialog.newInstance(this, 1, list);
            addDialog.setResultListener(entity -> {
                successAddRefresh();
            });
        } else {
            addDialog.setMotorcades(list);
        }
        addDialog.show();
        addDialog.setTitle("确认添加");
        if (currDriver != null && !TextUtils.isEmpty(currPhone)) {
            ProprietaryDriverEntity driverEntity = new ProprietaryDriverEntity();
            driverEntity.setName(currDriver.getName());
            driverEntity.setTelphone(currPhone);
            driverEntity.setDriverNo(currDriver.getUserNo());
            addDialog.setDriverInfo(driverEntity);
        }
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }
}
